//
//  HLArticleViewController.m
//  HLAerospace
//
//  Created by hulian-ios on 17/9/15.
//  Copyright © 2017年 hulian-LB. All rights reserved.
//

#import "HLArticleViewController.h"
#import "MBProgressHUD+HL.h"
#import "HttpRequestManager.h"
#import <MJExtension/MJExtension.h>
#import "HLCourseDetail.h"
#import "HLFoldCourse.h"
#import "HLUserInfo.h"
#import <WebKit/WebKit.h>
#import "HLDiscussViewController.h"
#import "HLNoteViewController.h"
#import "HLCollect.h"
#import "HLMoreCourse.h"
#import "HLDataBaseManager.h"
#import "HLFoldCourse.h"
#import "HLDownLoaderManager.h"

@interface HLArticleViewController ()

@property (nonatomic ,strong) WKWebView *wkWebView;
@property (nonatomic ,weak) UIButton *collectButton;

@end

@implementation HLArticleViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setUI];
    
    if (self.courseDetail.filePath && self.courseDetail.filePath.length > 0) {
        [self setupBottomView];

    }else{
        [self loadRequest];
    }
}

- (void)setUI
{
    self.navigationItem.title = @"文章详情";
    
    WKWebView *web = [[WKWebView alloc]init];
    web.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight - 60);
    self.wkWebView = web;
    web.backgroundColor = HLRGB(245, 245, 245);
    [self.view addSubview:web];
}

- (void)setupBottomView
{
    UIView *bottomView = [UIView new];
    bottomView.frame = CGRectMake(0, ScreenHeight - 60, ScreenWidth, 60);
    bottomView.backgroundColor = HLRGB(245, 245, 245);
    [self.view addSubview:bottomView];
    
    UIButton *discussButton = [UIButton buttonWithType:UIButtonTypeCustom];
    discussButton.backgroundColor = kColorMineBlueBG;
    discussButton.frame = CGRectMake(0.05*ScreenWidth, 12.5, 0.4*ScreenWidth, 35);
    discussButton.layer.cornerRadius = 17.5f;
    discussButton.clipsToBounds = YES;
    [discussButton setTitle:@"参与讨论" forState:UIControlStateNormal];
    [discussButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [discussButton addTarget:self action:@selector(discussContent:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:discussButton];
    
    UIButton *onteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    onteButton.frame = CGRectMake(ScreenWidth - 90, 9, 40, 40);
    [onteButton setImage:[UIImage imageNamed:@"home_article_note"] forState:UIControlStateNormal];
    [onteButton addTarget:self action:@selector(onteContent:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:onteButton];
    
    
    UIButton *downloadButton = [UIButton buttonWithType:UIButtonTypeCustom];
    downloadButton.frame = CGRectMake(ScreenWidth - 50, 10, 40, 40);
    [downloadButton setImage:[UIImage imageNamed:@"home_course_download"] forState:UIControlStateNormal];
    [downloadButton addTarget:self action:@selector(addDataBaseCourseDetail:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:downloadButton];
    
    
    UIButton *collectButton = [UIButton buttonWithType:UIButtonTypeCustom];
    collectButton.frame = CGRectMake(ScreenWidth - 140, 9, 42, 42);
    [collectButton setImage:[UIImage imageNamed:@"home_article_collect"] forState:UIControlStateNormal];
    [collectButton addTarget:self action:@selector(collectContent:) forControlEvents:UIControlEventTouchUpInside];
    self.collectButton = collectButton;
    [bottomView addSubview:collectButton];
    
}

- (void)loadRequest
{
    [MBProgressHUD show];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"course_id"] = self.foldCourse.wkid;
    params[@"user_id"] = [HLUserInfo account].userid;
    params[@"sign"] = [kHLRequestGetCourseDetail signStr];
    __weak typeof(self) weakSelf = self;
    [[HTTPRequestManager defaultManager] HTTPGetRequestWithApiName:kHLRequestGetCourseDetail parameters:params success:^(NSURLSessionDataTask * _Nonnull dataTask, id  _Nonnull responseObject){
        [MBProgressHUD hideHUD];
        if ([responseObject[@"code"] integerValue] == 200) {
            [weakSelf setupBottomView];

            weakSelf.courseDetail = [HLCourseDetail mj_objectWithKeyValues:responseObject[@"data"]];
            [weakSelf.wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:weakSelf.courseDetail.play_url]]];
            [weakSelf.collectButton setImage:[UIImage imageNamed:([weakSelf.courseDetail.state isEqualToString:@"0"] ? @"home_article_collect":@"home_article_collect_click")] forState:UIControlStateNormal];
            if (!weakSelf.isSkipFormHistoryRecord) {
                [weakSelf addCourseToDataBase];
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nonnull dataTask, NSError * _Nonnull error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showErrorMessage:@"网络超时"];
    }];
}


- (void)addCourseToDataBase
{
    HLCollect *colecte = [HLCollect new];
    colecte.course_pic = self.moreCourse.pic.length == 0 ? self.history_record_pic_url:self.moreCourse.pic;
    colecte.course_name = self.courseDetail.name;
    colecte.course_type = @"0";
    colecte.father = self.moreCourse.name;
    colecte.num = self.courseDetail.num;
    colecte.course_id = self.courseDetail.ID;
    
    if ([HLDataBaseManager isHistoryRecord:colecte]) {
        [HLDataBaseManager removeHistoryRecord:colecte];
        [HLDataBaseManager addHistoryRecord:colecte];
    }else{
        [HLDataBaseManager addHistoryRecord:colecte];
    }
}

- (void)discussContent:(UIButton *)button
{
    HLDiscussViewController *discuss = [HLDiscussViewController new];
    discuss.courseDetail = self.courseDetail;
    discuss.courseID = self.foldCourse.wkid;
    [self.navigationController pushViewController:discuss animated:YES];
}

- (void)onteContent:(UIButton *)button
{
    HLNoteViewController *note = [HLNoteViewController new];
    note.courseID = self.foldCourse.wkid;
    [self.navigationController pushViewController:note animated:YES];
}

- (void)collectContent:(UIButton *)button
{
    [MBProgressHUD show];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"course_id"] = self.foldCourse.wkid;
    params[@"user_id"] = [HLUserInfo account].userid;
    params[@"sign"] = [kHLRequestFavourate signStr];
    params[@"type"] = [self.courseDetail.state isEqualToString:@"0"] ? @"1" : @"0";
    __weak typeof(self) weakSelf = self;
    [[HTTPRequestManager defaultManager] HTTPGetRequestWithApiName:kHLRequestFavourate parameters:params success:^(NSURLSessionDataTask * _Nonnull dataTask, id  _Nonnull responseObject){
        [MBProgressHUD hideHUD];
        if ([responseObject[@"code"] integerValue] == 200) {
            weakSelf.courseDetail.state = responseObject[@"sc_state"];
            
            [MBProgressHUD showSuccessMessage:([weakSelf.courseDetail.state isEqualToString:@"0"] ? @"取消收藏":@"收藏成功")];
            [button setImage:[UIImage imageNamed:([weakSelf.courseDetail.state isEqualToString:@"0"] ? @"home_course_collect":@"home_course_collect_click")] forState:UIControlStateNormal];
        }
        
    } failure:^(NSURLSessionDataTask * _Nonnull dataTask, NSError * _Nonnull error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showErrorMessage:@"网络超时"];
    }];
    
}

- (void)addDataBaseCourseDetail:(UIButton*)button
{
    if ([HLDataBaseManager isDownloadedFile:self.courseDetail] ) {
        [MBProgressHUD showSuccessMessage:@"已经下载完成"];
        return;
    }
    
    if ([HLDataBaseManager isDownloadingFile:self.courseDetail]) {
        [MBProgressHUD showSuccessMessage:@"已经加入下载队列"];
        return;
    }
    [MBProgressHUD showTipMessageInView:@"已加入下载列表"];
    
    __weak typeof(self)weakSelf = self;
    [[HLDownLoaderManager shareInstance]hl_downLoader:[NSURL URLWithString:self.courseDetail.play_url] downLoadInfo:^(long long totalSize) {
        self.courseDetail.totalSize = totalSize;
        if ([HLDataBaseManager isDownloadingFile:self.courseDetail]) {
            [HLDataBaseManager removeDownloadingFile:self.courseDetail];
        }
        [HLDataBaseManager addDownloadingFile:self.courseDetail];
        
        [[NSNotificationCenter defaultCenter]postNotificationName:kHLDownLoadTableViewReloadDataNotifacation object:nil];
        
    } progress:^(float progress) {
        
    } success:^(NSString *filePath) {
        /**** 强引用 ****/
        __strong typeof (weakSelf)strongSelf = weakSelf;
        strongSelf.courseDetail.filePath = filePath;
        //正在下载的数据库 删除记录
        if ([HLDataBaseManager isDownloadingFile:strongSelf.courseDetail]) {
            [HLDataBaseManager removeDownloadingFile:strongSelf.courseDetail];
        }
        //成功下载 加入成功表
        if ([HLDataBaseManager isDownloadedFile:strongSelf.courseDetail]) {
            [HLDataBaseManager removeDownloadedFile:strongSelf.courseDetail];
        }
        [HLDataBaseManager addDownloadedFile:strongSelf.courseDetail];
        
        [[NSNotificationCenter defaultCenter]postNotificationName:kHLDownLoadTableViewReloadDataNotifacation object:nil];
        
    } failed:^{
    }];
    
}



@end
